package com.yellow.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yellow.constant.RedisConstant;
import com.yellow.dao.SetMealDao;
import com.yellow.enity.PageResult;
import com.yellow.enity.QueryPageBean;
import com.yellow.pojo.Setmeal;
import com.yellow.service.SetMealService;
import com.yellow.utils.AliyunOSSUtils;
import com.yellow.utils.AliyunSMSUtis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, int[] checkgroupIds) {
        //获取图片名称存储到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        //添加套餐,并且返回自增主键
        setMealDao.addMeal(setmeal);
        //添加套餐和检查组的关系
        Map<String, Object> map = new HashMap<>();
        map.put("setmealId", setmeal.getId());
        map.put("checkgroupIds", checkgroupIds);
        setMealDao.addMealAndCheckGroupRel(map);
    }

    @Override
    public PageResult PageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.PageQuery(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> findAllsetmeals() {
        //根据文件名，查询oos
        List<Setmeal> setmeals = setMealDao.findAllsetmeals();
        List<String> imglist = new ArrayList<>();
        for (Setmeal setmeal : setmeals) {
            imglist.add(setmeal.getImg());
        }
        List<String> urls = AliyunOSSUtils.getURL(imglist);
        //给图片名称赋值
        for (int i = 0; i < setmeals.size(); i++) {
            setmeals.get(i).setImg(urls.get(i));
        }

        return setmeals;
    }

    @Override
    public Setmeal findById(int id) {
        Setmeal setmeal = setMealDao.findById(id);
        String img = setmeal.getImg();
        String url = AliyunOSSUtils.getURL(img);
        setmeal.setImg(url);
        return setmeal;
    }

}
